<template>
  <div class="main-container">
    <div class="top-box" style="display: flex; justify-content: space-between; align-items: center;">
      <div>
        <h3>车位数据统计</h3>
      </div>

      <el-select
          v-model="value"
          placeholder="选择某一小区查看"
          size="large"
          style="width: 240px;"
          @change="handleSelectChange"
      >
        <el-option
            v-for="item in communityList"
            :key="item.id"
            :label="item.communityName"
            :value="item.id"
        />
      </el-select>

      <el-button
          type="primary"
          size="large"
          style="margin-left: 10px;"
          @click="clearSelection"
      >
        清空选择
      </el-button>
    </div>

    <div class="middle-boxes-container">
      <div class="left-middle-box">
        <div id="barChart" style="width: 100%; height: 400px;"></div>
      </div>
      <div class="right-middle-box">
        <div id="pieChart" style="width: 100%; height: 400px;"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, nextTick } from 'vue';
import axios from "axios";
import { ElMessage, ElButton } from "element-plus";
import * as echarts from "echarts";

export default defineComponent({
  name: 'ThreeBoxesComponent',
  data() {
    return {
      unFreeCount: 0,
      freeCount: 0,
      repairingCount: 0,
      orderedCount: 0,
      purchasedCount: 0,
      monthlyRentedCount: 0,
      yearlyRentedCount: 0,
      temporaryCount: 0,
      communityList: null,
      communityId: "",
      value: null
    };
  },
  mounted() {
    this.fetchTypeCounts();
    this.fetchCommunityList();
  },
  methods: {
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response);
        this.communityList = response.data.data;
        console.log('this.community', this.communityList);
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    async getCountByUseType(communityId, useType) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/parking-use/page', {
          headers: {
            Authorization: token
          },
          params: {
            current: 1,
            size: 10,
            communityId: communityId,
            useType: useType
          }
        });
        return response.data.data.total;
      } catch (error) {
        ElMessage.error('获取车位使用性质记录数量失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
        return 0;
      }
    },
    async getCountByStatus(communityId, status) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/parking/page', {
          headers: {
            Authorization: token
          },
          params: {
            current: 1,
            size: 10,
            communityId: communityId,
            status: status
          }
        });
        return response.data.data.total;
      } catch (error) {
        ElMessage.error('获取对应车位状态记录数量失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
        return 0;
      }
    },
    async fetchTypeCounts() {
      // 如果没有选择小区，则不传递 communityId 参数
        const communityId = this.communityId || null;
        this.unFreeCount = await this.getCountByStatus(communityId, '已占用');
        this.orderedCount = await this.getCountByStatus(communityId,  '已预定');
        this.repairingCount = await this.getCountByStatus(communityId,  '维修中');
        this.freeCount = await this.getCountByStatus(communityId, '空闲');
        this.purchasedCount = await this.getCountByUseType(communityId, '购买');
        this.monthlyRentedCount = await this.getCountByUseType(communityId, '月租');
        this.yearlyRentedCount = await this.getCountByUseType(communityId, '年租');
        this.temporaryCount = await this.getCountByUseType(communityId, '临时');
        await nextTick();
        this.drawBarChart();
        this.drawPieChart();
    },
    drawBarChart() {
      const chartDom = document.getElementById('barChart');
      if (chartDom) {
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '车位状态数据状态分布',
            subtext: `总记录数: ${this.unFreeCount + this.orderedCount + this.repairingCount + this.freeCount}`,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['已占用', '已预定', '维修中', '空闲'],
            left: '10%',
            top: '10%'
          },
          xAxis: {
            type: 'category',
            data: ['已占用', '已预定', '维修中', '空闲']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              type: 'bar',
              data: [this.unFreeCount, this.orderedCount, this.repairingCount, this.freeCount],
              itemStyle: {
                color: '#5793f3',
              },
              barWidth: '20%'
            }
          ]
        };
        myChart.setOption(option);
      }
    },
    drawPieChart() {
      const chartDom = document.getElementById('pieChart');
      if (chartDom) {
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '车位使用性质数据分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['购买', '月租', '年租', '临时']
          },
          series: [
            {
              name: '车位使用性质比例',
              type: 'pie',
              radius: '50%',
              center: ['50%', '50%'],
              data: [
                { value: this.purchasedCount, name: '购买' },
                { value: this.monthlyRentedCount, name: '月租' },
                { value: this.yearlyRentedCount, name: '年租' },
                { value: this.temporaryCount, name: '临时' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };
        myChart.setOption(option);
      }
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchTypeCounts();
    },
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchTypeCounts();
    }
  }
});
</script>

<style scoped>
.main-container {
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.top-box {
  display: flex;
  flex-direction: row;
  padding: 20px;
  align-items: center;
  text-align: center;
  margin-bottom: 10px;
}

.middle-boxes-container {
  display: flex;
  justify-content: space-between;
}

.left-middle-box,
.right-middle-box {
  padding: 20px;
  width: 48%;
  border-radius: 3px;
  text-align: center;
  /* 增加外边距 */
  margin: 0 10px;
  /* 修改背景透明度 */
  background-color: rgb(253, 253, 253);
}
</style>







